package rsexplorer.rstree;

import rsexplorer.utils.FieldFilter;
import java.lang.reflect.Array;

public class ArrayFieldTreeNode extends FieldContainerTreeNode {

    protected boolean arrayToBig;
    
    private int maxArrayIndex;

    public ArrayFieldTreeNode(Object userObject, Object fieldObject, int maxArrayIndex) {
        this(userObject, fieldObject, null, maxArrayIndex, 0);
    }

    public ArrayFieldTreeNode(Object userObject, Object fieldObject, FieldFilter filter, int maxArrayIndex) {
        this(userObject, fieldObject, filter, maxArrayIndex, 0);
    }

    protected ArrayFieldTreeNode(Object userObject, Object fieldObject, int maxArrayIndex, int level) {
        this(userObject, fieldObject, null, maxArrayIndex, level);
    }

    protected ArrayFieldTreeNode(Object userObject, Object fieldObject, FieldFilter filter, int maxArrayIndex, int level) {
        super(userObject, fieldObject, filter, level);
        //setSortChildren(false);
        this.maxArrayIndex = maxArrayIndex;
        init();
    }

    private void init() {
        this.removeAllChildren();
        
        int length = Array.getLength(fieldObject);

        int searchLength = Math.min(maxArrayIndex, length);

        arrayToBig = length > maxArrayIndex;
        setUserObject(userObject + (arrayToBig ? " (Array size exceeds " + maxArrayIndex + ", showing " + searchLength + " indices of " + length + ")" : ""));

        for (int i = 0; i < searchLength; i++) {
            Object indexObject = Array.get(fieldObject, i);

            if (indexObject == null)
                indexObject = "null";

            addChildField("["+i+"]", indexObject);
        }
    }

    public int getMaxArrayIndex() {
        return maxArrayIndex;
    }

    public boolean arrayToBig() {
        return arrayToBig;
    }

    public void update(Object userObject, Object fieldObject) {
        int length = Array.getLength(fieldObject);

        int searchLength = Math.min(maxArrayIndex, length);

        arrayToBig = length > maxArrayIndex;
        setUserObject(userObject + (arrayToBig ? " (Array size exceeds " + maxArrayIndex + ", showing " + searchLength + " indices of " + length + ")" : ""));

        int j = 0;
        for (int i = 0; i < children.size(); i++) {
            Object indexObject = Array.get(fieldObject, i);

            if (indexObject == null)
                indexObject = "null";

            updateChildField(i, "["+i+"]", indexObject);
            j++;
        }
    }
}
